import { Button, Space, Table, Message, Input, Pagination, Drawer, Select, Form, Popconfirm, Link } from '@arco-design/web-react';
import { fetchUserList, fetchUserDetail, fetchUserDetailUpdate, fetchChangeUserStatus, fetchUserAdd, synUser } from '../../../../../api/common'
import {useState} from 'react';
import { regExpConfig } from '../../../../../configs/regular.config'
const Option = Select.Option;
const formItemLayout = {
  wrapperCol: {
    span: 24,
  },
};
function UserTable({state, setState}){
    const [addUserVisiale, setUserAddVisiable] = useState(false)
    const [userVisiale, setUserVisiable] = useState(false)
    const [search, setSearch] = useState(false)
    const [modifyform, setForm] = useState({})
    const [keyIterater, next] = useState(3456)
    const InputSearch = Input.Search;
    const columns = [
        {
          title: '姓名',
          dataIndex: 'chineseName',
          key: 'chineseName'
        },
        {
            title: '职务',
            dataIndex: 'position',
            key: 'position'
        },
        {
            title: '账号',
            dataIndex: 'username',
            key: 'username'
        },
        {
          title: '账号状态',
          dataIndex: 'status',
          key: 'status',
          render: (col, record, index) => (
              <span>
                {record.status === 0 ? <Link status='success'>正常</Link> : <Link status='error'>冻结</Link>}
              </span>
          ),
        },
        {
          title: '角色',
          dataIndex: 'roles',
          key: 'roles',
          render: (col, record, index) => {
            let list = []
            list.map(obj =>{
                console.log(obj)
            })
            if (record.roles){
            list.push(record.roles.map(obj => (<span>{obj.roleName}</span>)))
            }
            return list
          }
        },
        {
          title: '操作',
          dataIndex: 'operate',
          render: (col, record, index) => {
                return(
                    <Space >
                      <Button type='text' style={{padding: '0'}} onClick={userDetailHandle(record)}>详情</Button>|
                      <Popconfirm
                        focusLock
                        title={`${record.status == 0 ? '冻结' : '解封'}用户`}
                        content=''
                        onOk={() => {
                          fetchChangeUserStatus({id: record.id, status: !record.status},
                            (res)=>{
                              Message.success(res.msg)
                              changeUserStatus(record.id)
                            },
                            (error)=>{
                              Message.error(error)
                            })
                        }}
                        onCancel={() => {
                          Message.error({
                            content: 'cancel',
                          });
                        }}
                      >
                        <Button type='text' style={{padding: '0'}}>{record.status == 0 ? '冻结' : '解封'}用户</Button>
                      </Popconfirm>
                      </Space>
                )
          }
        },
    ];

    function changeUserStatus(id){
      console.log('id' ,id)
      setState(state=>{
        return{
          ...state,
          userListResult: {
            ...state.userListResult,
            loading: true
          }
        }
      })
      let tmp = [...state.userListResult.list]
      if (!(tmp && tmp.length > 0)){
        return
      }
      for(let i = 0; i < tmp.length; i++){
        if (tmp[i].id == id){
          tmp[i].status = tmp[i].status == 0 ? 1 : 0
        }
      }
      setState(state=>{
        return{
          ...state,
          userListResult: {
            ...state.userListResult,
            loading: false,
            list: tmp
          }
        }
      })
    }

    function UserAdd(){
      const [form] = Form.useForm();
      const [confirmLoading, setConfirmLoading] = useState(false);
      let list = []
      return(
        <Drawer
          width={414}
          title={<span>添加用户 </span>}
          visible={addUserVisiale}
          confirmLoading={confirmLoading}
          onOk={() => {
            form.validate().then((data) => {
              setConfirmLoading(true);
              data.roles = list
              data.status = 0
              data.id = keyIterater
              next(keyIterater=>keyIterater+1)
              fetchUserAdd({userInfo: data},
                (res)=>{
                  setState(state=>{
                    return{
                      ...state,
                      userListResult: {
                        ...state.userListResult,
                        list: [
                          ...state.userListResult.list,
                          data
                        ]            
                      }
                    }
                  })
                  Message.success(res.msg)
                  setConfirmLoading(false)
                  setUserAddVisiable(false)
                },
                (error)=>{ 
                  Message.error(error)
                  setConfirmLoading(false)
                })
            }).catch(error=>{
              Message.error('数据格式不正确')
              setConfirmLoading(false);
            });
          }}
          onCancel={() => {
            setUserAddVisiable(false);
          }}
        >
          <Form {...formItemLayout} form={form} layout='vertical'>
            <Form.Item label='名称' field='chineseName' 
              rules={[
                { required: true, minLength: 2, maxLength: 16, message: '名字长度必须在2-16之间'},
                ]}>
              <Input placeholder='用户名' />
            </Form.Item>
            <Form.Item label='身份证' required field='idcardNo' 
              rules={[
                { required: true },
                { match: regExpConfig.IDcard, message: '身份证格式不对' }
                ]}>
              <Input placeholder='输入身份证' />
            </Form.Item>
            <Form.Item label='登陆用户' required field='username' 
              rules={[  
                { required: true, maxLength: 10, minLength: 6, message: '用户名只能在6-10个字之间' },
                ]}>
              <Input placeholder='登陆用户' />
            </Form.Item>
            <Form.Item label='输入密码' required field='password' 
              rules={[
                { required: true , minLength: 10, maxLength: 16, message: '密码必须在6-16位之间'},
                { match: regExpConfig.isNotChina, message: '密码不能是中文' }
                ]}>
              <Input placeholder='输入密码' type='password'/>
            </Form.Item>
            <Form.Item label='手机号' required field='phoneNo'
              rules={[
                { required: true },
                { match: regExpConfig.phoneNo, message: '手机号格式不对' }
                ]}>
              <Input placeholder='手机号码' />
            </Form.Item>
            <Form.Item label='手机短号' required field='shortNo' 
              rules={[{ match: regExpConfig.isInt, message: '短号格式不对,必须是数字' }]}>
              <Input placeholder='手机短号' />
            </Form.Item>
            <Form.Item label='职务' required field='posotion'>
              <Input placeholder='职务' />
            </Form.Item>
            <Form.Item label='角色' required field='roles'>
              <Select
                mode='multiple'
                placeholder='Please select'
                style={{ width: 345 }}
                onSelect={(event, op)=>{
                  list.push({...op.extra})
                }}
                onDeselect={(event, op)=>{
                  for( let i = 0; i < list.length; i++ ){
                    if (list[i].id == event){
                      list.splice(i, 1)
                      return
                    }
                  }
                }}
                allowClear
              >
                {state.userRoleSetResult.list.map((role) => (
                  <Option key={role.id} value={role.id} extra={role}>
                    {role.roleName}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Form>
        </Drawer>
      )
    }

    function userDetailHandle(record){
      return ()=>{
        fetchUserDetail({id: record.id},
          (res)=>{
            setForm(record)
            setUserVisiable(true)
          },
          (error)=>{
            Message.error(error)
          })
      }
    }

    function Userdetail(){
      const [form] = Form.useForm();
      const [confirmLoading, setConfirmLoading] = useState(false);
      let list = modifyform.roles ? [...modifyform.roles] : []
      function updateDetailHandle(){
        form.validate().then(data=>{
          fetchUserDetailUpdate({...data},
            (res)=>{
              data.roles = list
              data.status = modifyform.status
              setConfirmLoading(true);
              let tmp = [...state.userListResult.list]
              for (let i = 0; i < tmp.length; tmp++){
                if (tmp[i].id == data.id){
                  tmp[i] = data
                  break
                }
              }
              setState(state=>{
                return{
                  ...state,
                  userListResult: {
                    ...state.userListResult,
                    list: tmp         
                  }
                }
              })
              Message.success('修改成功')
              setConfirmLoading(false);
              setUserVisiable(false)
            },
            (error)=>{
              Message.error(error)
              setConfirmLoading(false);
              setUserVisiable(false)
            })
        }).catch(error=>{
          Message.error(error)
          setConfirmLoading(false);
        })
      }
      return(
        <Drawer
          width={414}
          title={<span>详情 </span>}
          visible={userVisiale}
          confirmLoading={confirmLoading}
          onOk={() => {
            form.validate().then((res) => {
              setConfirmLoading(true);
              updateDetailHandle()
            }).catch(error=>{
              Message.info('输入格式不对')
            });
          }}
          onCancel={() => {
            setUserVisiable(false);
          }}
        >
          <Form {...formItemLayout} form={form} layout='vertical'>
          <Form.Item label='id' required field='id' initialValue={modifyform.id ? modifyform.id : ''}>
              <Input placeholder={modifyform.chineseName ? modifyform.chineseName : '请输入名称'} disabled/>
            </Form.Item>
            <Form.Item label='名称' required field='chineseName' 
               rules={[
                { required: true, minLength: 2, maxLength: 16, message: '名字长度必须在2-16之间'},
                ]}
              initialValue={modifyform.chineseName ? modifyform.chineseName : ''}>
              <Input placeholder={modifyform.chineseName ? modifyform.chineseName : '请输入名称'}  />
            </Form.Item>
            <Form.Item label='身份证' required field='idcardNo' 
               rules={[
                { required: true },
                { match: regExpConfig.IDcard, message: '身份证格式不对' }
                ]}
              initialValue={modifyform.idcardNo ? modifyform.idcardNo : ''} >
              <Input placeholder={modifyform.idcardNo ? modifyform.idcardNo : '请输入身份证'}/>
            </Form.Item>
            <Form.Item label='登陆用户' required field='username' 
               rules={[  
                { required: true, maxLength: 10, minLength: 6, message: '用户名只能在6-10个字之间' },
                ]}
              initialValue={modifyform.username ? modifyform.username : ''}>
              <Input placeholder={modifyform.username ? modifyform.username : '请输入用户名'}/>
            </Form.Item>
            <Form.Item label='修改密码' required field='password' 
              rules={[
                { required: true , minLength: 10, maxLength: 16, message: '密码必须在6-16位之间'},
                { match: regExpConfig.isNotChina, message: '密码不能是中文' }
                ]}
              initialValue={modifyform.password ? modifyform.password : null}>
              <Input placeholder='修改密码' type='password' />
            </Form.Item>
            <Form.Item label='手机号' required field='phoneNo' 
              rules={[{ match: regExpConfig.isInt, message: '短号格式不对,必须是数字' }]}
              initialValue={modifyform.phoneNo ? modifyform.phoneNo : ''}>
              <Input placeholder={modifyform.phoneNo ? modifyform.phoneNo : '请输入手机号'} />  
            </Form.Item>
            <Form.Item label='手机短号' field='shortNo' 
              rules={[{ match: regExpConfig.isInt, message: '短号格式不对,必须是数字' }]}
              initialValue={modifyform.shortNo ? modifyform.shortNo : ''}>
              <Input placeholder={modifyform.shortNo ? modifyform.shortNo : '请输入手机短号'} />
            </Form.Item>
            <Form.Item label='职务'  field='posotion'  initialValue={modifyform.posotion ? modifyform.posotion : ''}>
              <Input placeholder={modifyform.posotion ? modifyform.posotion : '请输入职务'} />
            </Form.Item>
            <Form.Item label='角色'  field='roles' initialValue={modifyform.roles ? [].push(modifyform.roles.map(role=>{return role.id})) : []}>
            <Select
              mode='multiple'
              placeholder='Please select'
              style={{ width: 345 }}
              onSelect={(event, op)=>{
                list.push({...op.extra})
                console.log('list: ', list)
              }}
              onDeselect={(event, op)=>{
                for( let i = 0; i < list.length; i++ ){
                  if (list[i].id == event){
                    list.splice(i, 1)
                    console.log('list: ', list)
                    return
                  }
                }
              }}
              allowClear
            >
              {state.userRoleSetResult.list.map((role) => (
                <Option key={role.id} value={role.id} extra={role}>
                  {role.roleName}
                </Option>
              ))}
            </Select>
            </Form.Item>
          </Form>
        </Drawer>
      )
    }

    function searchUserList(value){
        setState((state)=>{
          return{
            ...state,
            userListResult: {
              ...state.userListResult,
              loading: true
            }
          }
        })
        fetchUserList({
          moduletype: state.moduletype,
          searchKey: state.searchKey
        },
        (res)=>{
            setState((state)=>{
              return{
                  ...state,
                  userListResult: {
                      ...state.userListResult,
                      list: res.data.list,
                      loading: false  
                  },
                  searchKey: {
                    ...state.searchKey,
                    pageSize: res.data.pageSize,
                    pageNo: res.data.pageNo,
                    total: res.data.totalCount
                }
              }
          })
        },
        (error)=>{
          Message.error(error)
      })
    }

    function searchKeyChange(value){
        setState(state=>{
          return{
            ...state,
            searchKey: {
              ...state.searchKey,
              keyword: value
            }
          }
        })
    }

    function synUserInfo(){
      setState(state=>{
        return{
          ...state,
          userListResult: {
            ...state.userListResult,
            loading: true
          }
        }
      })
      synUser({},
        (res)=>{
          Message.success(res.msg)
          setState(state=>{
            return{
              ...state,
              userListResult: {
                ...state.userListResult,
                loading: false
              }
            }
          })
        },
        (error)=>{
          Message.error(error.msg)
          setState(state=>{
            return{
              ...state,
              userListResult: {
                ...state.userListResult,
                loading: false
              }
            }
          })
        })
    }

    return(
        <div style={{boxSizing: 'border-box' ,padding: '14px', height: '100%', position: 'relative'}}>
             <Space wrap  style={{position: 'absolute', left: '10px'}}>
                <InputSearch
                  searchButton='Search'
                  loading={search}
                  value={state.searchKey.keyword}
                  placeholder='Enter keyword to search'
                  style={{ width: 350 }}
                  onSearch={searchUserList}
                  onChange={searchKeyChange}
                />
              </Space>
            <div style={{position: 'absolute', top: '70px', left: '10px', width: '90%'}}>
              <Table columns={columns}
                loading={state.userListResult.loading}
                data={state.userListResult.list}
                borderCell = {true} 
                pagination = {false}/>
            </div>
            <div style={{position: 'absolute', bottom: 30,right: 40, width: '100%'}}>
              <div style={{display: 'inline-block'}}>
                <Space>
                  <Button type='primary' 
                    onClick={()=>{
                      setUserAddVisiable(true)
                    }}>新增人员
                  </Button>
                  <Button type='primary' onClick={synUserInfo}>同步人员</Button>
                </Space>
              </div>
              <div style={{display: 'inline-block'}}>
                <Pagination total={state.searchKey.total}
                  current={state.searchKey.pageNo}
                  pageSize={state.searchKey.pageSize}
                  sizeCanChange={true}
                  onChange={(number, size)=>{
                    Message.success('pageNumber: '+number+' pageSize: '+size)
                  }} />
              </div>
            </div>
            {addUserVisiale ? <UserAdd />: null}
            {userVisiale ? <Userdetail /> : null}
        </div>
    )
}

export default UserTable